﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System.Threading.Tasks;

using Utils;

namespace System.Net.Http
{
    public static class HttpClientExtensions
    {

        public static async Task<R> ReadAsResultAsync<R>(this Task<HttpResponseMessage> httpContent, bool ignoreStatusCode = false)
        {
            var next = await httpContent;
            return await next.ReadAsResultAsync<R>(ignoreStatusCode);
        }

        public static async Task<R> ReadAsResultAsync<R>(this HttpResponseMessage httpContent, bool ignoreStatusCode = false)
        {
            if (!ignoreStatusCode && !httpContent.IsSuccessStatusCode)
            {
                throw Error.SystemError("请求失败：请检查地址是否正确");
            }
            var responseJson = await httpContent.Content.ReadAsJTokenAsync();
            var responseResult = responseJson.ToObject<R>(JsonContent.DefaultJsonSerializer);
            return responseResult;
        }


        public static async Task<JToken> ReadAsJTokenAsync(this Task<HttpResponseMessage> httpContent, bool ignoreStatusCode = false)
        {
            var next = await httpContent;
            return await next.ReadAsJTokenAsync(ignoreStatusCode);
        }


        public static async Task<JToken> ReadAsJTokenAsync(this HttpResponseMessage httpContent, bool ignoreStatusCode = false)
        {
            if (!ignoreStatusCode && !httpContent.IsSuccessStatusCode)
            {
                throw Error.SystemError("请求失败：请检查地址是否正确");
            }
            return await httpContent.Content.ReadAsJTokenAsync();
        }

        public static async Task<JToken> ReadAsJTokenAsync(this HttpContent httpContent)
        {
            if (httpContent is JsonContent jsonContent)
            {
                return jsonContent.GetJToken();
            }
            else
            {
                string str = await httpContent.ReadAsStringAsync();
                if (str == null) throw Error.SystemError("请求失败：无数据返回");
                try
                {
                    return JToken.Parse(str);
                }
                catch (Exception)
                {
                    await Console.Out.WriteLineAsync(str);
                    throw;
                }
            }
        }

        public static async Task<J> ReadAsJAsync<J>(this HttpContent httpContent) where J : JToken
        {
            if (httpContent is JsonContent jsonContent)
            {
                return (J)jsonContent.GetJToken();
            }
            else
            {
                string str = await httpContent.ReadAsStringAsync();

                if (str == null) throw Error.SystemError("请求失败：无数据返回");
                try
                {
                    return (J)JToken.Parse(str);
                }
                catch
                {
                    throw Error.SystemError("无效返回：" + str);
                }
            }
        }

        public static string AppendQuery(this string url, object query)
        {
            var urlParams = query?.ToDictionary();
            if (urlParams == null) return url;
            url += url.Contains("?") ? "&" : "?";
            url += urlParams.ToUrlQuery();
            return url;
        }


    }
}
